package com.wans.guli.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.wans.guli.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wans.guli.common.utils.PageUtils;
import com.wans.guli.common.utils.Query;

import com.wans.guli.product.dao.BrandDao;
import com.wans.guli.product.entity.BrandEntity;
import com.wans.guli.product.entity.CategoryBrandRelationEntity;
import com.wans.guli.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                new QueryWrapper<BrandEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateBrandEntity(BrandEntity brand) {
        // 更新商品品牌
        if (!this.updateById(brand))
            throw new RuntimeException("商品品牌更新失败");
        // TODO 更新关联表

        if (StrUtil.isNotEmpty(brand.getName()))
            // 更新关联表 - 品牌名更新
            if (!categoryBrandRelationService.lambdaUpdate()
                    .eq(CategoryBrandRelationEntity::getBrandId, brand.getBrandId())
                    .set(CategoryBrandRelationEntity::getBrandName, brand.getName())
                    .update()
            )
                throw new RuntimeException("品牌名更新失败");

    }

    @Override
    @Transactional
    public void removeBrandByIds(Long[] brandId) {
        // 转数组
        List<Long> listBrandId = Arrays.asList(brandId);
        // TODO 关联表查询
        List<CategoryBrandRelationEntity> brandRelationEntities = categoryBrandRelationService.lambdaQuery().in(CategoryBrandRelationEntity::getBrandId, listBrandId).list();

        if (!brandRelationEntities.isEmpty())
            throw new RuntimeException("关联表有数据");

        // 删除商品品牌
        if (!this.removeByIds(listBrandId))
            throw new RuntimeException("商品品牌删除失败");
    }

}